package com.chromatic.competition.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {

    /**
     * 发起POST请求
     *
     * @param url       请求URL
     * @param headerMap 请求头信息
     * @param jsonText  请求体内容
     * @param charset   字符集编码
     * @return 响应结果
     */
    public String doPost(String url, Map<String, String> headerMap, String jsonText, String charset) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            headerMap.forEach(httpPost::addHeader);
            if (StringUtils.isNotBlank(jsonText)) {
                byte[] bytes = jsonText.getBytes(StandardCharsets.UTF_8);
                ByteArrayEntity entity = new ByteArrayEntity(bytes);
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            return (resEntity != null) ? EntityUtils.toString(resEntity, charset) : null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}